import 'package:flutter/services.dart';
import 'package:bubble/bubble.dart';
import 'package:flutter/material.dart';
import 'package:znmm/config/app_asset.dart';

import '../model/chat_msg_model.dart';
import 'chat_date_format.dart';

typedef MessageWidgetBuilder = Widget Function(ChatMsgModel message);
typedef OnBubbleClick = void Function(
    ChatMsgModel message, BuildContext ancestor);

//typedef 定义了一个函数类型 HiSelectionArea
typedef HiSelectionArea = Widget Function(
    {required Text child, required ChatMsgModel message});

class ChatMsgWidget extends StatelessWidget {
  final ChatMsgModel message;

  /// the font-family of the [content].
  final String? fontFamily;

  /// the font-size of the [content].
  final double fontSize;

  /// the size of the [avatar].
  final double avatarSize;

  /// the text-color of the [content].
  final Color? textColor;

  /// Background color of the message
  final Color? backgroundColor;
  final MessageWidgetBuilder? messageWidget;

  //单击
  final OnBubbleClick? onBubbleTap;

  //长按
  final OnBubbleClick? onBubbleLongPress;

  final HiSelectionArea? hiSelectionArea;

  const ChatMsgWidget({
    required GlobalKey key,
    required this.message,
    this.fontFamily,
    this.fontSize = 16.0,
    this.textColor,
    this.backgroundColor,
    this.messageWidget,
    this.avatarSize = 40,
    this.onBubbleTap,
    this.onBubbleLongPress,
    this.hiSelectionArea,
  }) : super(key: key);

  double get contentMargin => avatarSize + 10;

  String get senderInitials {
    if (message.ownerName == null) return "";
    List<String> chars = message.ownerName!.split(" ");
    if (chars.length > 1) {
      return chars[0];
    } else {
      return message.ownerName![0];
    }
  }

  Widget get _buildCircleAvatar {
    String strImage = AppAsset.tabHome;
    if (message.ownerType == OwnerType.sender) {
      strImage = AppAsset.tabCenter;
    }

    return ClipOval(
      child: Image.asset(
        strImage,
        width: avatarSize,
        height: avatarSize,
        fit: BoxFit.fill,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (messageWidget != null) {
      return messageWidget!(message);
    }
    Widget content = message.ownerType == OwnerType.receiver
        ? _buildReceiver(context)
        : _buildSender(context);
    return Column(
      children: [
        if (message.showCreatedTime) _buildCreatedTime(),
        Padding(
          padding: const EdgeInsets.only(top: 10, left: 5, right: 5),
          child: content,
        ),
      ],
    );
  }

  Widget _buildReceiver(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        _buildCircleAvatar,
        Flexible(
          child: Bubble(
              margin: BubbleEdges.fromLTRB(10, 0, contentMargin, 0),
              stick: true,
              nip: BubbleNip.leftTop,
              color: backgroundColor ?? const Color.fromRGBO(233, 232, 252, 10),
              alignment: Alignment.topLeft,
              child: _buildContentText(TextAlign.left, context)),
        ),
      ],
    );
  }

  Widget _buildSender(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Flexible(
          child: Bubble(
              margin: BubbleEdges.fromLTRB(contentMargin, 0, 10, 0),
              stick: true,
              nip: BubbleNip.rightTop,
              color: backgroundColor ?? Colors.white,
              alignment: Alignment.topRight,
              child: _buildContentText(TextAlign.left, context)),
        ),
        _buildCircleAvatar
      ],
    );
  }

  Widget _buildContentText(TextAlign align, BuildContext context) {
    Widget text = Text(
      message.content,
      textAlign: align,
      style: TextStyle(
          fontSize: fontSize,
          color: textColor ?? Colors.black,
          fontFamily: fontFamily),
    );
    if (hiSelectionArea != null) {
      text = hiSelectionArea!.call(child: text as Text, message: message);
    }
    return InkWell(
        onTap: () =>
            onBubbleTap != null ? onBubbleTap!(message, context) : null,
        onLongPress: () {
          print("onLongPress");

          showDialog(
            context: context,
            builder: (BuildContext context) {
              return Center(
                child: AlertDialog(
                  title: const Text('Copy Text?'),
                  content: const Text('Do you want to copy this text?'),
                  actions: [
                    TextButton(
                      onPressed: () {
                        Clipboard.setData(ClipboardData(text: message.content));

                        Navigator.of(context).pop();
                        // 执行复制操作
                      },
                      child: const Text('Copy'),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: const Text('Cancel'),
                    ),
                  ],
                ),
              );
            },
          );
        },
        child: text);
  }

  Widget _buildCreatedTime() {
    String showT = ChatDateFormat.format(message.createdAt, dayOnly: false);
    return Container(
      padding: const EdgeInsets.only(top: 10),
      child: Text(showT),
    );
  }
}
